import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'

/**
 * 表单数据持久化存储
 * 解决页面切换时表单数据丢失的问题
 * 支持用户偏好设置控制持久化行为
 */
export const useFormDataStore = defineStore('formData', () => {
  // 检查用户偏好设置
  function checkUserPreferences() {
    const persistPageSwitch = (localStorage.getItem('pph_persist_page_switch') ?? '1') === '1'
    const persistBrowserRestart = (localStorage.getItem('pph_persist_browser_restart') ?? '1') === '1'
    const expireDays = parseInt(localStorage.getItem('pph_state_expire_days') ?? '7')

    return {
      persistPageSwitch,
      persistBrowserRestart,
      expireDays
    }
  }

  // 检查数据是否过期
  function isDataExpired(timestamp: number, expireDays: number): boolean {
    if (expireDays === 0) return false // 永久保存
    const expireTime = expireDays * 24 * 60 * 60 * 1000 // 转换为毫秒
    return Date.now() - timestamp > expireTime
  }
  // 数据录入页面表单数据
  const dataEntryForm = ref<any>({})
  
  // 目标值管理页面搜索表单数据
  const targetSearchForm = ref<any>({})
  
  // 预估值管理页面搜索表单数据
  const estimateSearchForm = ref<any>({})
  
  // 报表分析页面搜索表单数据
  const reportsSearchForm = ref<any>({})
  
  // 记录维护页面搜索表单数据
  const recordMaintenanceSearchForm = ref<any>({})

  // 页面状态数据
  const pageStates = reactive({
    dataEntry: {
      lastOrderNumber: '',
      lastMaterialCode: '',
      lastProductName: '',
      calculationResult: null,
      fetchedOrderInfo: null
    },
    targetManagement: {
      currentPage: 1,
      pageSize: 20,
      lastSearchParams: null
    },
    estimateManagement: {
      currentPage: 1,
      pageSize: 20,
      lastSearchParams: null
    },
    reports: {
      currentPage: 1,
      pageSize: 20,
      lastSearchParams: null,
      selectedFields: [],
      fieldOrder: []
    },
    recordMaintenance: {
      currentPage: 1,
      pageSize: 20,
      lastSearchParams: null
    }
  })

  // 保存数据录入表单数据
  function saveDataEntryForm(formData: any) {
    dataEntryForm.value = { ...formData }
    
    // 同时保存到localStorage作为备份
    try {
      localStorage.setItem('pph_data_entry_form', JSON.stringify({
        data: formData,
        timestamp: Date.now()
      }))
    } catch (error) {
      console.warn('保存数据录入表单到localStorage失败:', error)
    }
  }

  // 获取数据录入表单数据
  function getDataEntryForm() {
    // 优先从内存获取
    if (Object.keys(dataEntryForm.value).length > 0) {
      return dataEntryForm.value
    }
    
    // 从localStorage恢复
    try {
      const saved = localStorage.getItem('pph_data_entry_form')
      if (saved) {
        const parsed = JSON.parse(saved)
        // 检查数据是否过期（24小时）
        if (Date.now() - parsed.timestamp < 24 * 60 * 60 * 1000) {
          dataEntryForm.value = parsed.data
          return parsed.data
        } else {
          // 清除过期数据
          localStorage.removeItem('pph_data_entry_form')
        }
      }
    } catch (error) {
      console.warn('从localStorage恢复数据录入表单失败:', error)
    }
    
    return {}
  }

  // 清除数据录入表单数据
  function clearDataEntryForm() {
    dataEntryForm.value = {}
    localStorage.removeItem('pph_data_entry_form')
  }

  // 保存搜索表单数据
  function saveSearchForm(pageType: string, formData: any) {
    // 直接根据pageType设置对应的ref
    switch (pageType) {
      case 'target':
        targetSearchForm.value = { ...formData }
        break
      case 'estimate':
        estimateSearchForm.value = { ...formData }
        break
      case 'reports':
        reportsSearchForm.value = { ...formData }
        break
      case 'recordMaintenance':
        recordMaintenanceSearchForm.value = { ...formData }
        break
    }

    // 保存到localStorage
    try {
      localStorage.setItem(`pph_${pageType}_search`, JSON.stringify({
        data: formData,
        timestamp: Date.now()
      }))
    } catch (error) {
      console.warn(`保存${pageType}搜索表单失败:`, error)
    }
  }

  // 获取搜索表单数据
  function getSearchForm(pageType: string) {
    const preferences = checkUserPreferences()

    // 如果用户关闭了页面切换保持，返回空对象
    if (!preferences.persistPageSwitch) {
      return {}
    }

    // 优先从内存获取
    let memoryData: any = {}
    switch (pageType) {
      case 'target':
        memoryData = targetSearchForm.value
        break
      case 'estimate':
        memoryData = estimateSearchForm.value
        break
      case 'reports':
        memoryData = reportsSearchForm.value
        break
      case 'recordMaintenance':
        memoryData = recordMaintenanceSearchForm.value
        break
    }

    if (Object.keys(memoryData).length > 0) {
      return memoryData
    }

    // 如果用户关闭了浏览器重启保持，不从localStorage恢复
    if (!preferences.persistBrowserRestart) {
      return {}
    }

    // 从localStorage恢复
    try {
      const saved = localStorage.getItem(`pph_${pageType}_search`)
      if (saved) {
        const parsed = JSON.parse(saved)
        // 检查数据是否过期
        if (!isDataExpired(parsed.timestamp, preferences.expireDays)) {
          // 设置到对应的ref
          switch (pageType) {
            case 'target':
              targetSearchForm.value = parsed.data
              break
            case 'estimate':
              estimateSearchForm.value = parsed.data
              break
            case 'reports':
              reportsSearchForm.value = parsed.data
              break
            case 'recordMaintenance':
              recordMaintenanceSearchForm.value = parsed.data
              break
          }
          return parsed.data
        } else {
          // 数据过期，清除
          localStorage.removeItem(`pph_${pageType}_search`)
        }
      }
    } catch (error) {
      console.warn(`从localStorage恢复${pageType}搜索表单失败:`, error)
    }

    return {}
  }

  // 保存页面状态
  function savePageState(pageType: keyof typeof pageStates, stateData: any) {
    if (pageType in pageStates) {
      Object.assign(pageStates[pageType], stateData)
    }
    
    // 保存到localStorage
    try {
      localStorage.setItem(`pph_${pageType}_state`, JSON.stringify({
        data: stateData,
        timestamp: Date.now()
      }))
    } catch (error) {
      console.warn(`保存${pageType}页面状态失败:`, error)
    }
  }

  // 获取页面状态
  function getPageState(pageType: keyof typeof pageStates) {
    // 优先从内存获取
    if (pageType in pageStates) {
      const memoryState = pageStates[pageType]
      if (Object.keys(memoryState).length > 0) {
        return memoryState
      }
    }
    
    // 从localStorage恢复
    try {
      const saved = localStorage.getItem(`pph_${pageType}_state`)
      if (saved) {
        const parsed = JSON.parse(saved)
        // 检查数据是否过期（1小时）
        if (Date.now() - parsed.timestamp < 60 * 60 * 1000) {
          if (pageType in pageStates) {
            Object.assign(pageStates[pageType], parsed.data)
          }
          return parsed.data
        } else {
          localStorage.removeItem(`pph_${pageType}_state`)
        }
      }
    } catch (error) {
      console.warn(`从localStorage恢复${pageType}页面状态失败:`, error)
    }
    
    return pageStates[pageType] || {}
  }

  // 清除所有表单数据
  function clearAllFormData() {
    dataEntryForm.value = {}
    targetSearchForm.value = {}
    estimateSearchForm.value = {}
    reportsSearchForm.value = {}
    recordMaintenanceSearchForm.value = {}
    
    // 清除localStorage
    const keys = [
      'pph_data_entry_form',
      'pph_target_search',
      'pph_estimate_search', 
      'pph_reports_search',
      'pph_recordMaintenance_search'
    ]
    
    keys.forEach(key => {
      localStorage.removeItem(key)
    })
  }

  // 保存订单信息（数据录入页面专用）
  function saveOrderInfo(orderNumber: string, orderInfo: any) {
    pageStates.dataEntry.lastOrderNumber = orderNumber
    pageStates.dataEntry.fetchedOrderInfo = orderInfo
    
    // 保存到localStorage
    try {
      localStorage.setItem('pph_last_order_info', JSON.stringify({
        orderNumber,
        orderInfo,
        timestamp: Date.now()
      }))
    } catch (error) {
      console.warn('保存订单信息失败:', error)
    }
  }

  // 获取订单信息
  function getOrderInfo(orderNumber?: string) {
    // 如果指定了订单号，检查是否匹配
    if (orderNumber && pageStates.dataEntry.lastOrderNumber === orderNumber) {
      return pageStates.dataEntry.fetchedOrderInfo
    }
    
    // 从localStorage恢复
    try {
      const saved = localStorage.getItem('pph_last_order_info')
      if (saved) {
        const parsed = JSON.parse(saved)
        // 检查数据是否过期（1小时）且订单号匹配
        if (Date.now() - parsed.timestamp < 60 * 60 * 1000) {
          if (!orderNumber || parsed.orderNumber === orderNumber) {
            pageStates.dataEntry.lastOrderNumber = parsed.orderNumber
            pageStates.dataEntry.fetchedOrderInfo = parsed.orderInfo
            return parsed.orderInfo
          }
        } else {
          localStorage.removeItem('pph_last_order_info')
        }
      }
    } catch (error) {
      console.warn('从localStorage恢复订单信息失败:', error)
    }
    
    return null
  }

  return {
    // 状态
    dataEntryForm,
    targetSearchForm,
    estimateSearchForm,
    reportsSearchForm,
    recordMaintenanceSearchForm,
    pageStates,
    
    // 方法
    saveDataEntryForm,
    getDataEntryForm,
    clearDataEntryForm,
    saveSearchForm,
    getSearchForm,
    savePageState,
    getPageState,
    clearAllFormData,
    saveOrderInfo,
    getOrderInfo
  }
})
